#include "SessionManager.h"

SessionManager::SessionManager() {
	logger.setFileName(FILE_NAME_SESSION_MANAGER_LOGGER);
}

//@author A0094701J
//1. Checks if the toggletask directory exists in the home directory.
//2. Creates the directory if it does not exist and creates a .txt file.
//3. Opens the directory if it exists and checks if the .txt file exists.
//4. If it exists, opens the .txt file and loads the session.
//5. If it does not exist, creates the .txt file.

//Notes:
//1. Utilizes the QDir, found in the Qt core library. This dependency must
//be included in the release version for it to work.
bool SessionManager::isSession(QString &userFeedback, ostringstream &readFile) {
    QDir Dir(TOGGLETASK_DIR);
    QString fileName = FILE_NAME;
    bool isDir = true;

    if (!Dir.exists()) {
        Dir.mkdir(TOGGLETASK_DIR);
        isDir = Dir.setCurrent(TOGGLETASK_DIR);
        userFeedback = createFile(fileName);
        return !isDir;
    }
    else {
        isDir = Dir.setCurrent(TOGGLETASK_DIR);
        QString QFileName = fileName.toStdString().c_str();

        if (Dir.exists(QFileName)) {
            userFeedback = MESSAGE_SESSION_LOADED;
            readFile = loadLastSession(FILE_NAME);
            return isDir;
        }
        else {
            userFeedback = createFile(fileName);
            return !isDir;
        }
    }
}

//@author A0080384E
void SessionManager::storeThisSession(QVector<Task> taskList){
    QString fileName = FILE_NAME;
    if (!saveTask.is_open()) {
        saveTask.open(fileName.toStdString().c_str());
    }

    QVector<Task>::iterator iter;

    for (iter = taskList.begin(); iter != taskList.end(); ++iter) {
		saveTask << (iter->getTitle()).toStdString() << SPACE << DELIMITER << SPACE;
		saveTask << (iter->getStartDateTime()).toString().toStdString() << SPACE << DELIMITER << SPACE;
        saveTask << (iter->getEndDateTime()).toString().toStdString() << SPACE << DELIMITER << SPACE;
        if ((iter->getTaskStatus() == Task::TaskStatus::COMPLETE)) {
			saveTask << COMPLETE_CHAR <<"\n";
        }
        else {
            saveTask << "\n";
        }
	}

	saveTask.close();
}

ostringstream SessionManager::loadLastSession(QString fileName) {
    if (!loadTask.is_open()) {
        loadTask.open(fileName.toStdString().c_str());
    }

    ostringstream readFile;
    string taskInfo;
    while (getline(loadTask, taskInfo)) {
        readFile << taskInfo << "\n";
    }

    loadTask.close();

    return readFile;
}

//@author A0094701J
//Creates and initialises a .txt file.
QString SessionManager::createFile(QString fileName) {
    saveTask.open(fileName.toStdString().c_str());
    loadTask.open(fileName.toStdString().c_str());
    return MESSAGE_FILE_CREATED;
}
